﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MvcEngine.Core.Repositories;
using MvcEngine.Core.Account;

namespace MvcEngine.Core.Validation
{
    /// <summary>
    /// Checks whether the user is unique in a data store
    /// </summary>
    public class UniqueUserNameValidatorAttribute : FieldValidatorAttribute
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="UniqueUserNameValidatorAttribute"/> class.
        /// </summary>
        public UniqueUserNameValidatorAttribute(string message)
            : base(message, true)
        {
            ErrorMessage = Message;
        }

        /// <summary>
        /// Determines whether the specified value is valid.
        /// </summary>
        /// <param name="value">The value.</param>
        /// <returns>
        /// 	<c>true</c> if the specified value is valid; otherwise, <c>false</c>.
        /// </returns>
        public override bool IsValid(object value)
        {
            if (value == null)
                return true;

            string val = value as string;
            if (val != null)
            {
                if (string.IsNullOrEmpty(val))
                    return true;
                return AccountManager.Current.GetUser(val) == null;
            }
            else
            {
                throw new InvalidOperationException("UniqueUserNameValidatorAttribute can applied only to string properties");
            }
        }
    }
}
